

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}


public class sol {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur1 = l1, cur2 = l2;
        ListNode ret = new ListNode();
        ListNode cur = ret;
        ListNode pre = null;
        while (cur1 != null && cur2 != null) {
            int num = cur1.val + cur2.val + cur.val;
            cur.val = num % 10;
            ListNode node = new ListNode();
            if (num >= 10) {
                node.val = 1;
            }
            cur.next = node;
            pre = cur;
            cur = node;
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        while (cur1 == null && cur2 != null) {
            int num = cur2.val + cur.val;
            cur.val = num % 10;
            ListNode node = new ListNode();
            if (num >= 10) {
                node.val = 1;
            }
            cur.next = node;
            pre = cur;
            cur = node;
            cur2 = cur2.next;
        }
        while (cur2 == null && cur1 != null) {
            int num = cur1.val + cur.val;
            cur.val = num % 10;
            ListNode node = new ListNode();
            if (num >= 10) {
                node.val = 1;
            }
            cur.next = node;
            pre = cur;
            cur = node;
            cur1 = cur1.next;
        }
        if (cur.val == 0) {
            pre.next = null;
        }
        return ret;
    }
}


